package com.d1708.zhanggm.springcloud.user.model.controller;

import com.d1708.zhanggm.springcloud.user.model.User;
import com.d1708.zhanggm.springcloud.user.model.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user/")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 根据Id查询用户
     * @param id
     * @return
     */
    @RequestMapping("getUserById")
    public User getUserById(@RequestParam("id") Integer id){
        log.info("userId:{}",id);
        return userService.getUserById(id);
    }

    @RequestMapping("getUserByUser")
    public User getUserByUser(@RequestBody User user){
        log.info("userId:{}",user.getId());
        /*try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        return userService.getUserById(user.getId());
    }

    /**
     * 根据Id，查询用户名称
     * @param id
     * @return
     */
    @RequestMapping("getUsernameById")
    public Object getUsernameById(@RequestParam("id") Integer id){
        String cacheKey = "user:"+id;
        //读取缓存数据
        User user = (User) redisTemplate.opsForValue().get(cacheKey);
        //如果已缓存，直接返回
        if(user!=null){
            return user;
        }
        //如果数据未缓存，查询数据库
        user =  userService.getUserById(id);
        redisTemplate.opsForValue().set(cacheKey,user);
        //设置缓存时间
        redisTemplate.expire(cacheKey,60, TimeUnit.SECONDS);
        return user;
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public Object login(@RequestParam("id") String username,@RequestParam("password") String password){
        //查询用户信息
        User user =  userService.getUsernameByUsername(username);
//        判断密码是否正确
        if(user!=null){
            String token = UUID.randomUUID().toString();
            //设置缓存
            redisTemplate.opsForValue().set(token,user);
            return token;
        }
        return null;
    }

    @PostMapping("getUserInfo")
    public Object getUserInfo(@RequestParam("token") String token){
        //查询用户信息
        User user = (User)redisTemplate.opsForValue().get(token);
        return user;
    }


}
